<html>
    <head>
        <title>Products</title>
        <link href="style.css" rel="stylesheet" type="text/css" media="screen" />
    </head>
    <body>
        <div id="logo">
            <h1><a href="#">Products</a></h1>
        </div>
        <form onsubmit="handleSubmit(); return false;">
            <div id='searchtab' name='searchtab' style='display:none;'>
                <div class='field'>
                    Search:<input type='text' id='searcht' name='searcht'>
                </div>
                <div class='field'>
                    <input type='button' class='buttons' value='Search' onclick='Search(document.all.searcht.value,0);'/><input  class='buttons' type='button' value='New' onclick='Load(0);'/><input type='button'  class='buttons' value='Exit' onclick='location.replace("index.html");'/>
                </div><span id="status">&nbsp;</span>
            </div>
            <div id='infotab' name='infotab' style='display:none;'>
            	<table width='200px' border='1'>
                    <tr>
                        <td>
                            <input type='button'  class='buttons' id='infobutton' onclick='ChangeTab(0);' value='Info'>
                        </td>
                        <td>
                            <input type='button' id='searchbutton'  class='buttons' onclick='ChangeTab(1);' value='Search' />
                        </td>
                        <td>
                            <input type='button' id='exitbutton'  class='buttons' onclick='location.replace("index.html");' value='Exit' />
                        </td>
                    </tr>
                </table>
                <input type='hidden' id='productid' name='productid' />
                <table class='field'>
                    <tr>
                        <td class='field'>
                            UPC:
                        </td>
                        <td class='field2'>
                            <input type='text' id='upc' name='upc' value='upc' />
                        </td>
                    </tr>
                    <tr>
                        <td class='field'>
                            Description:
                        </td>
                        <td class='field2'>
                            <input type='text' id='description' name='description' />
                        </td>
                    </tr>
                    <tr>
                        <td class='field'>
                            Brand:
                        </td>
                        <td class='field2'>
                            <input type='text' id='brand' name='brand' />
                        </td>
                    </tr>
                    <tr>
                        <td class='field'>
                            Model:
                        </td>
                        <td class='field2'>
                            <input type='text' id='model' name='model' />
                        </td>
                    </tr>
                    <tr>
                        <td class='field'>
                            Type
                        </td>
                        <td class='field2'>
                            <span id='ptypespan' name='ptypespan'>
                                <select id='producttype' name='producttype'>
                                </select>
                            </span>
                            <input type='button' class='buttons'onclick='javascript:location.replace("productTypes.html");' value='Add' />
                        </td>
                    </tr>
                    <tr>
                        <td class='field'>
                            Quantity
                        </td>
                        <td class='field2'>
                            <input type='button' class='buttons' id='delqty' onclick='AddOne("quantity",-1);' value='-' /><input type='button' class='buttons' id='addqty' value='+'  onclick='AddOne("quantity",1);'/><input type='text' style='width:50%' id='quantity' name='quantity' />
                        </td>
                    </tr>
                    <tr>
                        <td class='field'>
                            Ordered
                        </td>
                        <td class='field2'>
                            <input type='button' class='buttons' id='delqty' onclick='AddOne("ordered",-1);' value='-' /><input type='button' id='addqty' value='+' class='buttons' onclick='AddOne("ordered",1);'/><input type='text' style='width:50%;' id='ordered' name='ordered' />
                        </td>
                    </tr>
                    <tr>
                        <td class='field'>
                            Cost
                        </td>
                        <td class='field2'>
                            <input type='text' id='cost' name='cost' onfocus='ShowNumPad(this,0)' />
                        </td>
                    </tr>
                    <tr>
                        <td class='field'>
                            Price
                        </td>
                        <td class='field2'>
                            <input type='text' id='price' name='price' onfocus='ShowNumPad(this,0)' />
                        </td>
                    </tr>
                </table>
                <div class='field'>
                    <input type='button' class='buttons' value='Save' onclick='Save();'/><input type='button' class='buttons' value='Delete' onclick='Delete(document.all.productid.value);'/>
                </div>
            </div>
			<div id='numpad' name='numpad'>
            </div>
            
        </form>
        <!-- ====================================== -->
        <!-- End HTML code.  Begin JavaScript code. -->
        <script type="text/javascript" src="gears_init.js">
        </script>
        <script type="text/javascript" src="scripts.js">
        </script>
        <script>
            var db;
            
            var query = location.search;
            var searchBookmark = 0;
            var itemid = query.substring(query.indexOf("id=") + 3, query.length);
            init();
            try {
				loadProductTypes('');
			}
			catch(ex){}
            
            if (itemid != '') {
                var loadid = new Number(itemid); //converts to number to prevent injection
                Load(loadid);
            }
            else {
                document.all.productid.value = '0';
                Search('', 0);
				
            }
            
            
            function ChangeTab(item){
                        
                            if (item == 0) 
                                document.all.infotab.style.display = 'inline';
                            else 
                                document.all.infotab.style.display = 'none';
                            if (item == 1) //search
                                document.all.searchtab.style.display = 'inline';
                            else 
                                document.all.searchtab.style.display = 'none';
							if (item == 7) 
                                document.all.numpad.style.display = 'inline';
                            else 
                                document.all.numpad.style.display = 'none';
                           
                        }
            
            
            // Open this page's local database.
            function init(){
                var success = false;
                
                if (window.google && google.gears) {
                    try {
                        db = google.gears.factory.create('beta.database');
                        
                        if (db) {
                            db.open('psdb');
                            
                            if (itemid == 'reset') {
                                if (confirm('Reset DB?') == true) {
                                    db.execute('drop table if exists Product');
                                    alert('Done');
                                }
                                
                            }
                            
                            db.execute('create table if not exists Product' +
                            ' (id int primarykey,' +
                            ' UPC text,' +
                            ' description text,' +
                            ' brand text,' +
                            ' model text,' +
                            ' type text,' +
                            ' quantity real,' +
                            ' ordered real,' +
                            ' cost real,' +
                            ' price text' +
                            ')');
                            
                            //create indexes
                            db.execute('create index if not exists Productix on Product' +
                            ' (id,UPC,description,brand,model);');
                            
                            success = true;
                            
                        }
                        
                    } 
                    catch (ex) {
                        setError('Could not create database: ' + ex.message);
                        alert('Could not create database: ' + ex.message);
                    }
                }
                
                // Enable or disable UI elements
                
                var inputs = document.forms[0].elements;
                for (var i = 0, el; el = inputs[i]; i++) {
                    el.disabled = !success;
                }
                
            }
            
            function Save(){
                if (!google.gears.factory || !db) {
                    return;
                }
                
                
                var productidT = document.all.productid;
                var upcT = document.all.upc;
                var descriptionT = document.all.description;
                //validate required
                var upc = upcT.value;
                var description = descriptionT.value;
                if (upc == '' && description == '') {
                    alert('UPC or Description is required');
                    return;
                }
                var brandT = document.all.brand;
                var modelT = document.all.model;
                var typeT = document.all.producttype;
                var quantityT = document.all.quantity;
                var orderedT = document.all.ordered;
                var costT = document.all.cost;
                var priceT = document.all.price;
                var productid = productidT.value;
                
                var brand = brandT.value;
                var model = modelT.value;
                var type = typeT.value;
                var quantity = quantityT.value;
                var ordered = orderedT.value;
                var cost = costT.value;
                var price = priceT.value;
                //var currTime = new Date().getTime();
                // alert(productid);
                
                //insert or update
                if (productid == '0') {
                    //get the new id
                    var rs = db.execute('select max(id)+1 as pid from Product');
                    var newid = 0;
                    newid = rs.field(0);
                    
                    if (newid == null) 
                        newid = 1;
                    rs.close();
                    // Insert the new item.
                    // The Gears database automatically escapes/unescapes inserted values.
                    db.execute('Insert into Product (id, upc, description, brand, model, type, quantity, ordered, cost, price) values (?,?,?,?,?,?,?,?,?,?)', [newid, upc, description, brand, model, type, quantity, ordered, cost, price]);
                    alert('Product added.');
                }
                else {
                    db.execute('Update Product Set upc=?, description=?, brand=?, model=?, type=?, quantity=?, ordered=?, cost=?, price=? where id=?', [upc, description, brand, model, type, quantity, ordered, cost, price, productid]);
                    alert('Product updated.');
                }
                // Update the UI.
                //elm.value = '';
                //displayRecentPhrases();
            }
            
            function Delete(id){
                if (id > 0) {
                
                    var a = confirm('Delete the product?');
                    if (a != false) {
                    
                        db.execute('delete from product where  id='+ id);
                        alert('Product deleted!');//
                        //Load first record as default..or display a top 20 search? 
                        var rs = db.execute('select top 1 id from Product');
                        rs.close();
                        Search('', 0);
                    }
                }
                
            }
            
            function Search(search, option){
				
                ChangeTab(1);
                searchBookmark = searchBookmark + option;
                if (searchBookmark < 0) 
                    searchBookmark = 0;
                
                
                var recentPhrases = ['', '', ''];
                var query = 'select * from product where UPC like "%' + search + '%"';
                query += ' OR description like "%' + search + '%"';
                query += ' OR brand like "%' + search + '%"';
                query += ' OR model like "%' + search + '%"';
                query += ' OR [type] like "%' + search + '%"';
                query += ' ORDER BY UPC, brand asc limit 10 offset ' + searchBookmark;
                
                var status = document.all.status;
                var html = '<div class="field" >Search Results:</div>';//'Searching...' ;
                var rs = db.execute(query);
                var count = 0;
                while (rs.isValidRow()) {
                    if (count >= 10) 
                        break;
                    
                    html += SearchResult3(rs.field(0), rs.field(2) + ',' + rs.field(3), 'Price:' + formatNumber(rs.field(9), true), 'Qty:' + rs.field(6));
                    count++;
                    rs.next();
                }
                
                if (searchBookmark >= 10) 
                    html += "<a href=# onclick='Search(\"" + search + "\",-10);'>[Back]</a>";
                if (count >= 10) 
                    html += "<a href=# onclick='Search(\"" + search + "\",10);'>[Next]</a>";
                status.innerHTML = html;
                rs.close();
                
            }
            
            function Load(id){
                // var pidT = document.all.productid;
                // var id = pidT.value;
				ChangeTab(0);
				var status = document.all.status;
                status.innerHTML = '';
                var index = 0;
                
                var productidT = document.all.productid;
                var upcT = document.all.upc;
                var descriptionT = document.all.description;
                var brandT = document.all.brand;
                var modelT = document.all.model;
                var typeT = document.all.producttype;
                var quantityT = document.all.quantity;
                var orderedT = document.all.ordered;
                var costT = document.all.cost;
                var priceT = document.all.price;
                if (id > 0) {
                    var rs = db.execute('select * from product where id=' + id);
                    
                    productidT.value = id;
                    upcT.value = rs.field(1);
                    descriptionT = rs.field(2);
                    brandT.value = rs.field(3);
                    modelT.value = rs.field(4);
                    quantityT.value = rs.field(6);
                    orderedT.value = rs.field(7);
                    costT.value = formatNumber(rs.field(8), false);
                    priceT.value = formatNumber(rs.field(9), false);
                    loadProductTypes(rs.field(5));
                    
                    rs.close();
                }
                else {
                    productidT.value = 0;
                    upcT.value = '';
                    descriptionT = '';
                    brandT.value = '';
                    modelT.value = '';
                    quantityT.value = '0';
                    orderedT.value = '0';
                    costT.value = '0.00';
                    priceT.value = '0.00';
                    loadProductTypes('');
                }
            }
            
            function LoadX(){
            
                document.all.info.style.display = 'inline';
                
                var productid = '';
                var upc = '';
                var description = '';
                var brand = '';
                var model = '';
                var type = '';
                var quantity = '';
                var ordered = '';
                var cost = '';
                var price = '';
                
                
                //var xmlDoc = new  Document();
                if (window.XMLHttpRequest) {
                    xhttp = new XMLHttpRequest()
                }
                else {
                    xhttp = new ActiveXObject("Microsoft.XMLHTTP")
                }
                xhttp.open("GET", "products.xml", false);
                xhttp.send("");
                xmlDoc = xhttp.responseXML;
                alert(xhttp.responseText.split(/\n/g));
                return;
                var y = xmlDoc.getElementsByTagName("products");
                var i = new Number();
                
                
                for (i = 0; i < y.length; i++) {
                    x = y[i].childNodes; //a specific product
                    //if(i<3)
                    
                    //if (x[1].childNodes[0].nodeValue == id) //check if matches an id
                    // {
                    //  alert( x[17].childNodes[0].nodeValue);
                    productid = x[1].childNodes[0].nodeValue;
                    try {
                        upc = x[15].childNodes[0].nodeValue;
                    } 
                    catch (ex) {
                        upc = "";
                    }
                    try {
                        description = x[3].childNodes[0].nodeValue;
                    } 
                    catch (ex) {
                        description = "";
                    }
                    try {
                        brand = x[5].childNodes[0].nodeValue;
                    } 
                    catch (ex) {
                        brand = "";
                    }
                    try {
                        model = x[7].childNodes[0].nodeValue;
                    } 
                    catch (ex) {
                        model = "";
                    }
                    try {
                        quantity = x[11].childNodes[0].nodeValue;
                    } 
                    catch (ex) {
                        quantity = "0";
                    }
                    try {
                        ordered = x[13].childNodes[0].nodeValue;
                    } 
                    catch (ex) {
                        ordered = "0";
                    }
                    try {
                        cost = x[17].childNodes[0].nodeValue;
                    } 
                    catch (ex) {
                        cost = "0.00";
                    }
                    try {
                        price = x[19].childNodes[0].nodeValue;
                    } 
                    catch (ex) {
                        price = "0.00";
                    }
                    try {
                        type = x[9].childNodes[0].nodeValue;
                    } 
                    catch (ex) {
                        type = "";
                    }
                    
                    db.execute('Insert into Product (id, upc, description, brand, model, type, quantity, ordered, cost, price) values (?,?,?,?,?,?,?,?,?,?)', [productid, upc, description, brand, model, type, quantity, ordered, cost, price]);
                    document.all.status.innerHTML = "Status: " + i + "/" + y.length;
                    
                }
                
            }
            
            function LoadXPIE(){
                var pidT = document.all.pid;
                var id = pidT.value;
                
                var upcT = document.all.upc;
                var descriptionT = document.all.description;
                var brandT = document.all.brand;
                var modelT = document.all.model;
                var typeT = document.all.type;
                var quantityT = document.all.quantity;
                var orderedT = document.all.ordered;
                var costT = document.all.cost;
                var priceT = document.all.price;
                
                //alert('vars ok:' + pidT.value);
                loadTitle2();
                return;
                var xmlDoc;
                
                xmlDoc = loadXMLDoc("products.xml");
                alert('load ok');
                y = xmlDoc.getElementsByTagName("products");
                //alert()
                for (i = 0; i < y.length; i++) {
                    x = y[i].childNodes; //a specific product
                    if (i < 3) 
                        alert(x[3].childNodes[0].nodeValue);
                    if (x[1].childNodes[0].nodeValue == id) //check if matches an id
                    {
                        //alert( x[2].childNodes[0].nodeValue);
                        upcT.value = x[15].childNodes[0].nodeValue;
                        descriptionT.value = x[3].childNodes[0].nodeValue;
                        brandT.value = x[5].childNodes[0].nodeValue;
                        modelT.value = x[7].childNodes[0].nodeValue;
                        quantityT.value = x[11].childNodes[0].nodeValue;
                        orderedT.value = x[13].childNodes[0].nodeValue;
                        costT.value = x[17].childNodes[0].nodeValue;
                        priceT.value = x[19].childNodes[0].nodeValue;
                        loadProductTypes(x[9].childNodes[0].nodeValue);
                        /*
                         <productid>1</productid>
                         <description>Cuenta</description>3
                         <brand>Abono</brand>5
                         <model>Cuenta</model>7
                         <typeid>ABO</typeid>9
                         <qty>0</qty>11
                         <order>0</order>13
                         <upc>Abono</upc>15
                         <cost>0</cost>17
                         <priceA>0</priceA>19
                         <priceB>0</priceB>21
                         <status>1</status>23
                         */
                        break;
                    }
                    //else 
                    //document.getElementById("status").innerHTML = 'Searching...' + i;
                
                }
                
            }
            
            function loadProductTypes(sel){
                var rs = db.execute('select * from ProductType order by 2 desc');
                var index = 0;
                var ptypespan = document.all.ptypespan;
                var itext = '';
                itext += '<select name="producttype">';
                while (rs.isValidRow()) {
                    itext += '<option value="' + rs.field(0) + '"';
                    if (sel == rs.field(0)) 
                        itext += ' selected ';
                    itext += '>' + rs.field(1) + '</option>';
                    rs.next();
                }
                rs.close();
                itext += '</select>';
                //alert(itext);
                ptypespan.innerHTML = itext;
                
            }
            
            function AddOne(control, amount){
                var amount1 = new Number(amount);
                var amount2 = new Number(document.all(control).value);
                var result = amount1 + amount2;
                
                document.all(control).value = result;
            }
        </script>
    </body>
</html>
